<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\model\activity\ActivityGoodsModel;
use app\model\activity\ActivityModel;
use app\model\goods\GoodsCommonModel;
use app\model\goods\GoodsModel;
use app\model\order\OrderGroupModel;
use think\Request;

/**
 * ActivityGoods
 * Class ActivityGoods
 * @package app\controller
 */
class ActivityGoods extends BaseEncryptController
{
    private $activity_model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = new ActivityGoodsModel();
        $this->activity_model = new ActivityModel();
    }

    /**
     * 分页列表
     * @param int $id
     * @param string $status
     * @param string $keyword
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     */
    public function getPage($id, $status = '', $keyword = '', $page = 1, $limit = 10)
    {
        $map = [
            'activity_id' => $id
        ];
        if (!empty($status)) {
            $map['status'] = $status;
        }
        $mapLike = [];
        if (!empty($keyword)) {
            $mapLike = [
                'g.goods_title' => "%" . $keyword . "%"
            ];
        }
        $data = $this->model->getPageActivityList($map, $mapLike, 'a.sort DESC', $page, $limit);
        $activity = $this->activity_model->getInfo($id);
        return self::returnMsg(1, [
            'other' => $activity,
            'totalCount' => $data['total'],
            'currentPage' => $data['current'],
            'pageList' => $data['dataList']
        ]);
    }

    /**
     * 单条信息
     * @param $id
     * @return \think\response\Json
     */
    public function getInfo($id)
    {
        $item = $this->model->getInfo($id, 'id,activity_id,attribute_ids,sell_price,condition,condition_time,goods_storage,sort,status');
        $goods_common_model = new GoodsCommonModel();
        if (!empty($item)) {
            $goods_data = $goods_common_model->where('attribute_ids', $item['attribute_ids'])->field('goods_sell_price')->find();
            $item['sell_price'] = floatval($item['sell_price'] / $goods_data['goods_sell_price']) * 100;
            return self::returnMsg(1, $item);
        } else {
            return self::returnMsg(1001);
        }
    }

    /**
     * 保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function onSave(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'activity_id' => $request->param('activity_id'),
            'attribute_ids' => $request->param('attribute_ids'),
            'sell_price' => $request->param('sell_price'),
            'condition' => $request->param('condition'),
            'condition_time' => $request->param('condition_time'),
            'goods_storage' => $request->param('goods_storage'),
            'sort' => $request->param('sort'),
            'status' => $request->param('status')
        ];
        if (intval($formData['goods_storage']) % intval($formData['condition']) != 0) {
            return self::returnMsg(991, [], "商品数量必须是团购人数的整数倍");
        }
        if (empty($formData['id'])) {
            $validate = 'app\validate\ActivityGoodsValidate.add';
        } else {
            $goods_common_model = new GoodsCommonModel();
            $goods_data = $goods_common_model->where('attribute_ids', $formData['attribute_ids'])->find();
            $formData['sell_price'] = floatval($goods_data['goods_sell_price']) * ($formData['sell_price'] / 100);
            $ret = $this->model->saveData($formData);
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $formData['admin_id'] = $this->currentUser['user_id'];
            $ret = $this->model->addGoods($formData);
            if (false === $ret) {
                return self::returnMsg(0);
            } else {
                return self::returnMsg(1);
            }
        }
    }

    /**
     * 修改库存
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function onChange(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'change' => $request->param('change'),
            'storage' => $request->param('storage')
        ];
        $validate = 'app\validate\ActivityGoodsValidate.change';
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            if (empty($formData['id'])) {
                return self::returnMsg(0);
            }
            $activity_goods = $this->model->getInfo($formData['id']);
            $goods_model = new GoodsModel();
            $storage = [
                'storage' => $formData['storage'],
                'target_id' => $activity_goods['activity_id'],
            ];
            $operate = [
                'operate' => 'activity',
                'admin_id' => $this->currentUser['user_id']
            ];
            if ($formData['change'] == 'add') {
                $remark = "活动商品增加库存";
            } else {
                $remark = "活动商品减少库存";
            }
            $ret = $goods_model->changeStore($activity_goods['goods_id'], $storage, $formData['change'], 0, $operate, $remark);
            if (false === $ret) {
                return self::returnMsg(0);
            } else {
                return self::returnMsg(1);
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     */
    public function onDelete($id)
    {
        $flag = $this->model->delGoods($id, $this->currentUser['user_id']);
        if (false !== $flag) {
            $this->model->delRedis($id);
            $this->model->redis->zRem($this->model->redis_key . ':rank', $id);
            $this->model->addToRecycle($id, 'ActivityGoodsModel', '活动商品管理', $this->currentUser['user_id'], $this->currentUser['user_type'], 'activity');
            return self::returnMsg(1);
        } else {
            return self::returnMsg(1002);
        }
    }

    /**
     * 保存状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function onStatus(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'status' => $request->param('status'),
        ];
        $validate = 'app\validate\ActivityGoodsValidate.upstatus';
        $result = $this->validate($formData, $validate);

        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }
}
